﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using NPinyin;
using YuuzleComic.DBUtility;
using System.Data.SqlClient;
using System.Net;
using YuuzleComic.Common;
using Microsoft.VisualBasic;

public partial class yzadmin_data_author : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    YuuzleComic.BLL.zz zzbll = new YuuzleComic.BLL.zz();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "save":
                    this.ProcessSave();
                    break;
                case "updatecolumn":
                    this.ProcessUpdateColumn();
                    break;
                case "allid":
                    this.ProcessAllId();
                    break;
                case "delete":
                    this.ProcessDelete();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessDelete()
    {
        JObject result = new JObject();
        try
        {
            DbHelperSQL.ExecuteSql("delete from zz where id in (" + Request["ids"] + ")");
            foreach (string id in Request["ids"].Split(','))
            {
                if (System.IO.File.Exists(Server.MapPath("~/list/author/" + id + ".html")))
                {
                    System.IO.File.Delete(Server.MapPath("~/list/author/" + id + ".html"));
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessAllId()
    {
        JObject result = new JObject();
        try
        {
            DataSet ds = DbHelperSQL.Query("select id from zz");
            List<int> idList = new List<int>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                idList.Add(Convert.ToInt32(dr["id"]));
            }
            result.Add("success", true);
            result.Add("allid", JArray.FromObject(idList));
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessSave()
    {
        JObject result = new JObject();
        try
        {
            YuuzleComic.Model.zz zz = new YuuzleComic.Model.zz();
            if (!string.IsNullOrEmpty(Request.Form["id"]))
            {
                zz = zzbll.GetModel(Convert.ToInt32(Request.Form["id"]));
            }
            zz.zzmc = Request.Form["zzmc"];
            zz.zm = Request.Form["zm"];
            zz.zztp = Request.Form["zztp"];
            zz.zzjs = YuuzleComic.Common.Input.convertHtml(Request.Form["zzjs"].Trim());
            zz.dqid = Convert.ToInt32(Request.Form["dqid"]);
            zz.tj = Request.Form["tj"] == "on";
            zz.zzbm = Request.Form["zzbm"];
            if (string.IsNullOrEmpty(zz.zm))
            {
                zz.zm = Pinyin.GetInitials(zz.zzmc).Substring(0, 1);
            }
            if (string.IsNullOrEmpty(Request.Form["id"]))
            {
                zz.id = zzbll.Add(zz);
            }
            else
            {
                zzbll.Update(zz);
            }
            this.process_zztp(zz);
            this.process_search(zz);
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void process_search(YuuzleComic.Model.zz zz)
    {
        DbHelperSQL.Query("delete from search where cid in (select cid from comics_zz where zzid=" + zz.id + ")");
        DataSet ds = DbHelperSQL.Query("select a.*,STUFF((SELECT ','+ z.zzmc FROM zz z join comics_zz cz on z.id=cz.zzid where cz.cid=a.id FOR XML PATH('')), 1, 1, '') zzmc from comics a where a.id in (select cid from comics_zz where zzid=" + zz.id + ") order by a.id desc");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            List<string> mclist = new List<string>();
            mclist.Add(dr["mhmc"].ToString().Trim());
            if (!string.IsNullOrEmpty(dr["mhbm"].ToString().Trim()))
            {
                foreach (string item in dr["mhbm"].ToString().Trim().Split(','))
                {
                    mclist.Add(item);
                }
            }
            //更新索引
            foreach (string mc in mclist)
            {
                SqlParameter[] parameters = {
					    new SqlParameter("@cid", SqlDbType.Int),
                        new SqlParameter("@mc1", SqlDbType.VarChar),
                        new SqlParameter("@mc2", SqlDbType.VarChar),
                        new SqlParameter("@mc3", SqlDbType.VarChar),
                        new SqlParameter("@mc4", SqlDbType.VarChar),
                        new SqlParameter("@mc5", SqlDbType.VarChar)};
                parameters[0].Value = Convert.ToInt32(dr["id"]);
                parameters[1].Value = mc;
                parameters[2].Value = Strings.StrConv(mc, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, System.Globalization.CultureInfo.CurrentCulture.LCID);
                parameters[3].Value = Pinyin.GetPinyin(mc).Replace(" ", "");
                parameters[4].Value = Pinyin.GetInitials(mc).Replace(" ", "");
                parameters[5].Value = dr["zzmc"].ToString().Trim();
                DbHelperSQL.Query("insert into search (cid,mc1,mc2,mc3,mc4,mc5) values(@cid,@mc1,@mc2,@mc3,@mc4,@mc5)", parameters);
            }
        }
    }

    private void process_zztp(YuuzleComic.Model.zz zz)
    {
        if (zz.zztp.Contains("http://"))
        {
            string filename = System.IO.Path.GetFileName(zz.zztp);
            WebClient wc = new WebClient();
            byte[] b = wc.DownloadData(zz.zztp);
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Input.ResizeImageFile(b, 120, 160));
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            img.Save(Server.MapPath("~/zpic/" + filename), System.Drawing.Imaging.ImageFormat.Jpeg);
            DbHelperSQL.ExecuteSql("update zz set zztp='" + filename + "' where id=" + zz.id);
        }
    }

    private void ProcessList()
    {
        try
        {
            JObject result = new JObject();
            int start = Convert.ToInt32(Request["start"]);
            int limit = Convert.ToInt32(Request["limit"]);
            string strWhere = "";
            if (Request["query"] == null)
            {
                strWhere = Request["id"] == null ? "" : "where id in (" + Request["id"] + ")";
            }
            else
            {
                strWhere = "where zzmc like @query or zzbm like @query";
            }
            string sql = "with tt as(Select ROW_NUMBER() Over(order by " + Request["sort"] + " " + Request["dir"] + ") as rowNum,* from ";
            sql += "(SELECT a.id, a.zzmc, a.zm, a.dqid, a.zztp, a.tj,a.zzbm, b.diqu, c.ccount FROM zz a LEFT OUTER JOIN diqu b ON a.dqid = b.id LEFT OUTER JOIN ";
            sql += "(SELECT t2.zzid, COUNT(t1.id) AS ccount FROM comics t1 join comics_zz t2 on t1.id=t2.cid GROUP BY t2.zzid) AS c ON a.id = c.zzid) t " + strWhere + ") select * from TT where rowNum between @start and @end";
            SqlParameter[] parameters = new SqlParameter[] { 
                 new SqlParameter("@query","%" +Request["query"] + "%"),
                new SqlParameter("@start",start + 1),
                new SqlParameter("@end",start + limit)
            };
            DataSet ds = DbHelperSQL.Query(sql, parameters);
            int total = Convert.ToInt32(DbHelperSQL.Query("select count(*) from zz " + strWhere, parameters).Tables[0].Rows[0][0]);
            JsonSerializer serializer = new JsonSerializer();
            serializer.Converters.Add(new JavaScriptDateTimeConverter());
            serializer.NullValueHandling = NullValueHandling.Ignore;
            result.Add("data", JArray.FromObject(ds.Tables[0], serializer));
            result.Add("total", total);
            json = result.ToString();
        }
        catch (Exception)
        {

            throw;
        }
    }

    private void ProcessSingle()
    {
        JObject result = new JObject();
        try
        {
            DataSet ds = DbHelperSQL.Query("select zzjs from zz where id=" + Request["id"]);
            result.Add("success", true);
            result.Add("data", JArray.FromObject(ds.Tables[0])[0]);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }


    private void ProcessUpdateColumn()
    {
        JObject result = new JObject();
        try
        {
            DbHelperSQL.ExecuteSql("update zz set " + Request["column"] + "=" + Request["value"] + " where id=" + Request["id"]);
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }
}